<?php

/**
 * 01CMS安装程序
 *
 * @package    01CMS
 * @subpackage install
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class IndexController extends Controller
{

    function __construct ()
    {
        parent::__construct();
        
        if (file_exists(APP_PATH . '/locked.txt'))
        {
            $this->backUrl = ROOT_DIR;
            $temp = '1CM';
            showInfo("你已经安装过0{$temp}S了！<br />如需重新安装请删除文件：" . APP_PATH . '/locked.txt');
        }
    }

    function index ($step = 1)
    {
        if ($step == 1)
        {
            $writeable = array();
            $writeable[] = array('file' => SYS_PATH . '/config', 'status' => is_writeable(SYS_PATH . '/config'));
            $writeable[] = array('file' => SYS_PATH . '/data', 'status' => is_writeable(SYS_PATH . '/data'));
            $writeable[] = array('file' => ROOT_PATH . '/01cms/config', 'status' => is_writeable(ROOT_PATH . '/01cms/config'));
            $writeable[] = array('file' => ROOT_PATH . '/01cms/data', 'status' => is_writeable(ROOT_PATH . '/01cms/data'));
            $writeable[] = array('file' => ROOT_PATH . '/www/config', 'status' => is_writeable(ROOT_PATH . '/www/config'));
            $writeable[] = array('file' => ROOT_PATH . '/www/data', 'status' => is_writeable(ROOT_PATH . '/www/data'));
            
            $soft = array();
            $soft['PHP']['version'] = substr(phpversion(), 0, 3);
            $soft['PHP']['status'] = $soft['PHP']['version'] > 5.0 ? TRUE : FALSE;
            $soft['MySQL']['version'] = '';
            $soft['MySQL']['status'] = function_exists('mysql_connect') ? TRUE : FALSE;
            $soft['GD']['version'] = '';
            
            if (! function_exists('phpinfo'))
            {
                $soft['GD']['status'] = function_exists('imagecreate') ? TRUE : FALSE;
            }
            else
            {
                ob_start();
                phpinfo(8);
                $phpinfo = ob_get_contents();
                ob_end_clean();
                $matches = array();
                if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $phpinfo, $matches))
                {
                    $soft['GD']['version'] = $matches[1];
                    $soft['GD']['status'] = TRUE;
                }
                else
                {
                    $soft['GD']['status'] = FALSE;
                }
            }
            
            $next = true;
            
            foreach ($writeable as $v)
            {
                if (! $v['status'])
                {
                    $next = false;
                    break;
                }
            }
            
            foreach ($soft as $v)
            {
                if (! $v['status'])
                {
                    $next = false;
                    break;
                }
            }
            
            $this->writeable = $writeable;
            $this->soft = $soft;
            $this->next = $next;
        
        }
        
        if ($step == 3 && ! file_exists(APP_PATH . '/locked.txt'))
        {
            file_put_contents(APP_PATH . '/locked.txt', "系统安装完成后会自动生成这个文件，如需重新安装请删除本文件！");
        }
        
        $this->Load->view('smarty', 'step' . $step);
    }

    function install ()
    {
        $data = $this->Load->post('hostname|数据库主机名不能为空,database|数据库名称不能为空,username|数据库用户名不能为空,password,prefix|数据表前缀不能为空,adminUsername|后台管理用户名不能为空,adminPassword|后台用户密码不能为空');
        
        if ($error = $this->Load->getError())
        {
            response($error);
        }
        
        $conn = @mysql_connect($data['hostname'], $data['username'], $data['password']);
        
        if (! $conn)
        {
            response("数据库连接失败，请检查配置是否正确");
        }
        
        $status = @mysql_query("CREATE DATABASE IF NOT EXISTS `{$data['database']}`;", $conn);
        
        if (! $status)
        {
            response("数据库创建失败，请检查是否有权限创建数据库。");
        }
        
        @mysql_close($conn);
        
        $config = array();
        $config['secret'] = md5(microtime(TRUE));
        $config['urlSuffix'] = '';
        $config['mysql']['hostname'] = $data['hostname'];
        $config['mysql']['username'] = $data['username'];
        $config['mysql']['password'] = $data['password'];
        $config['mysql']['database'] = $data['database'];
        $config['mysql']['prefix'] = $data['prefix'];
        $config['mysql']['pconnect'] = FALSE;
        $config['mysql']['charset'] = 'utf8';
        
        $configFile = SYS_PATH . '/config/config.php';
        
        if (! is_writeable($configFile))
        {
            response("配置文件不可写，无法继续安装：<br />{$configFile}");
        }
        
        $comment = "全局配置文件\n\n";
        $comment .= "secret：安装时自动生成的加密字符串，请勿修改\n";
        $comment .= "urlSuffix：URL伪后缀，用于URL重写时去掉入口文件名";
        
        $status = lib('Write')->phpArray($configFile, $config, $comment);
        
        if (empty($status))
        {
            response('配置文件写入失败');
        }
        
        Base::i()->Load->config = $config;
        
        $Model = model('Db');
        
        $query = '';
        $fp = fopen(APP_PATH . '/data/sql/01cms.sql', 'r');
        while (! feof($fp))
        {
            $line = rtrim(fgets($fp, 1024));
            if (ereg(";$", $line))
            {
                $query .= $line . "\n";
                $Model->query($query);
                $query = '';
            }
            else if (! ereg("^(//|--|/\*)", $line))
            {
                $query .= $line;
            }
        }
        fclose($fp);
        
        $Model->query("INSERT INTO `@@__admin_user` (`username`, `password`, `groupId`, `email`, `regTime`, `loginTime`, `loginIp`, `loginNum`) 
        VALUES ('{$data['adminUsername']}', '" . encrypt($data['adminPassword']) . "', 1, 'cms01@qq.com', '" . TIME . "', '" . TIME . "', '" . getIp() . "', 0);");
        
        response('安装成功，正在转向，请稍候...', true);
    }

    function check ($type = '')
    {
        $data = $this->Load->post('hostname|数据库主机名不能为空,username|数据库用户名不能为空,password');
        
        if ($error = $this->Load->getError())
        {
            $response['message'] = $error;
            $response['success'] = FALSE;
        }
        else
        {
            $status = @mysql_connect($data['hostname'], $data['username'], $data['password']);
            
            if ($status)
            {
                if ($type == 'database')
                {
                    $database = $this->Load->post('database', 'one');
                    $status = @mysql_select_db($database);
                    if ($status)
                    {
                        $response['message'] = '数据库已存在';
                        $response['success'] = TRUE;
                    }
                    else
                    {
                        $response['message'] = '数据库不存在，系统将会自动创建数据库';
                        $response['success'] = TRUE;
                    }
                
                }
                else
                {
                    $response['message'] = '数据库连接成功';
                    $response['success'] = TRUE;
                }
            }
            else
            {
                $response['message'] = '数据库连接失败';
                $response['success'] = FALSE;
            }
        }
        
        echo json_encode($response);
    }
}

//END